/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pubguru.data;

import com.sun.org.apache.bcel.internal.generic.AALOAD;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

/**
 *
 * @author Dao
 */
public class AuthorData {
    private static AuthorData _instance;
    public static AuthorData getInstance()
    {
        if (_instance == null)
            _instance = new AuthorData();
        return _instance;
    }
    
    private AuthorData()
    {
        authorData = new HashMap<>();
        mappingId = new HashMap<>();
        currIdAuthor = 0;
    }
    
    private HashMap<Integer, String> authorData;  //key : hashcode of value , value : author name
    
    private HashMap<Integer, Integer> mappingId;  //key : hashcode of author name , value : author id
    
    private int currIdAuthor;
    
    public void LoadData(String fileName) throws FileNotFoundException, IOException
    {
        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        br.readLine(); //ignore first line
        String str="";
        String[] tokens;
        String authorName;
        int authorId;
        int count = 1;
        int hashCode = 0;
        while ((str=br.readLine()) != null)
        {
            count++;
            tokens = str.split("\t");
            if (tokens.length == 2)
            {
                authorId = Integer.parseInt(tokens[0]);
                authorName = tokens[1];
                hashCode = authorName.hashCode();
                authorData.put(hashCode, authorName);
                mappingId.put(hashCode, authorId);
                currIdAuthor = authorId;
            }
            else
            {
                //System.out.println("Error at " + count + " " + fileName);
            }
        }
        br.close();
        fr.close();
    }
    
    public void AddAuthor(String authorName)
    {
        int hashCOde = authorName.hashCode();
        if (!authorData.containsKey(hashCOde))
        {
            AddNewAuthor(hashCOde, authorName);
        }     
    }
        
    private void AddNewAuthor(int hashCode,String authorName)
    {
        authorData.put(hashCode, authorName);
        currIdAuthor++;
        mappingId.put(hashCode, currIdAuthor);
    }
}
